package com.bawei.music;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 *  MediaPlayer的方法：
 *  （1）播放:start()
 *  （2）暂停:pause()
 *  （3）停止:stop()
 *  （4）释放资源:release()
 *  （5）是否正在播放:isPlaying()
 *  （6）获得当前进度：getCurrentPosition（）
 *  （7）获得总进度：getDuration()
 *   (8)播放指定进度：seekTo()
 *   (9)重置媒体资源：reset()
 *   (10)设置媒体资源：setDataSource(网址)
 *   (11)准备：prepare() 同步准备   prepareAsync() 异步准备：网络歌曲
 *   (12)三个监听
 *      a。准备监听：setOnPreparedListener()
 *      b。错误监听：setOnErrorListener()
 *      c。播放完毕监听：setOnCompleteListener()
 */
public class MainActivity extends AppCompatActivity {
    private SeekBar seekBar;
    private Button btStart;
    private Button btPre;
    private Button btNext;
    private Button btRandom;
    private Button btLoop;
    private Button btOrder;
    private Button btQuick;
    private Button btBack;
    private TextView tvCurrent;
    private TextView tvDuration;
    private MediaPlayer mMediaPlayer = new MediaPlayer();
    private List<Song> songs = new ArrayList();
    private Mode mode = Mode.ORDER;//播放模式 默认顺序
    private int currentPosition = 0;//当前播放音乐下标

    //定时器：不断获取歌曲的当前进度更新UI
    private Timer mTimer = new Timer();
    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initListener();
        initSongs();
        play();//播放歌曲
        initTimer();
    }

    /**
     * 定时器任务：每隔500毫秒获取歌曲的进度和总进度
     */
    private void initTimer() {
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                //子线程不能直接更新UI，通过handler在主线程更新UI
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {//主线程
                        tvCurrent.setText(getCurrentTime());//当前时间
                        tvDuration.setText(getDurationTime());//总时间
                        seekBar.setProgress(getProgress());//进度条的进度

                    }
                });

            }
        },0,500);

    }

    /**
     * 事件监听
     */
    private void initListener() {
        //播放暂停
        btStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startOrPause();
            }
        });
        //下一首
        btNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                next();
            }
        });
        //上一首
        btPre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pre();
            }
        });
        //循环
        btLoop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mode = Mode.LOOP;
            }
        });
        //顺序
        btOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mode = Mode.ORDER;
            }
        });
        //随机
        btRandom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mode = Mode.RANDOM;
            }
        });
        //快进
        btQuick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                quick();
            }
        });
        //快退
        btBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                back();
            }
        });
        //拖拽进度条
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {//进度条改变
                //progress 0-100
                if(fromUser){//来自用户的拖拽
                    seekTo(progress);
                    Log.d("ytx", "onProgressChanged: ");
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    /**
     * 初始化view：findViewById
     */
    private void initView() {
        seekBar = (SeekBar) findViewById(R.id.seek_bar);
        btStart = (Button) findViewById(R.id.bt_start);
        btPre = (Button) findViewById(R.id.bt_pre);
        btNext = (Button) findViewById(R.id.bt_next);
        btRandom = (Button) findViewById(R.id.bt_random);
        btLoop = (Button) findViewById(R.id.bt_loop);
        btOrder = (Button) findViewById(R.id.bt_order);
        btQuick = (Button) findViewById(R.id.bt_quick);
        btBack = (Button) findViewById(R.id.bt_back);
        tvCurrent = (TextView) findViewById(R.id.tv_current);
        tvDuration = (TextView) findViewById(R.id.tv_duration);

    }

    /**
     * 初始化数据
     */
    private void initSongs() {
        songs.add(new Song("再见","http://39.106.204.190:7777/mp3/36024806.mp3"));
        songs.add(new Song("句号","http://39.106.204.190:7777/mp3/1405283464.mp3"));
        songs.add(new Song("光年之外","http://39.106.204.190:7777/mp3/449818741.mp3"));
        songs.add(new Song("泡沫","http://39.106.204.190:7777/mp3/233931.mp3"));
    }

    /**
     * 切歌
     */
    public void play(){
        if(mMediaPlayer == null){
            mMediaPlayer = new MediaPlayer();
        }
        try {
            mMediaPlayer.reset();//注意：设置新资源前一定要记得重制
            mMediaPlayer.setDataSource(songs.get(currentPosition).getData());//设置歌曲的资源
            mMediaPlayer.prepareAsync();//异步准备
            //准备监听
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {//准备监听
                @Override
                public void onPrepared(MediaPlayer mp) {//准备完成
                    mMediaPlayer.start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 继续播放或暂停
     */
    public void startOrPause(){
        if(mMediaPlayer != null){
            if(mMediaPlayer.isPlaying()){//判断是否正在播放
                mMediaPlayer.pause();
                btStart.setText("播放");
            }else{
                mMediaPlayer.start();
                btStart.setText("暂停");
            }
        }
    }

    /**
     * 下一首 顺序：下标+1 随机：随机值 单曲：下标不变
     */
    public void next(){
        if(mode == Mode.ORDER){//顺序播放
            if(currentPosition == songs.size()-1){//是否为最后一首歌
                currentPosition = 0;
            }else{
                currentPosition++;
            }
        }else if(mode == Mode.RANDOM){//随机播放 0- 长度-1
            currentPosition = (int) (Math.random()*songs.size());
        }
        play();//切换歌曲
    }

    /**
     * 上一首 顺序：下标-1 随机：随机值 单曲：下标不变
     */
    public void pre(){
        if(mode == Mode.ORDER){//
            if(currentPosition == 0){//如果是第一首
                currentPosition = songs.size()-1;
            }else{
                currentPosition--;
            }
        }else if(mode == Mode.RANDOM){//随机播放 0- 长度-1
            currentPosition = (int) (Math.random()*songs.size());
        }
        play();//切换歌曲
    }

    /**
     * 快进
     */
    public void quick(){
        if(mMediaPlayer != null){
            //获得当前音乐播放进度
            int currentPosition = mMediaPlayer.getCurrentPosition();
            //进度+5秒
            currentPosition+=5*1000;
            //设置最新的进度
            mMediaPlayer.seekTo(currentPosition);

        }

    }

    /**
     * 快退
     */
    public void back(){
        if(mMediaPlayer != null){
            //获得当前音乐播放进度
            int currentPosition = mMediaPlayer.getCurrentPosition();
            //进度+5秒
            currentPosition-=5*1000;
            //设置最新的进度
            mMediaPlayer.seekTo(currentPosition);

        }
    }

    /**
     * 获得当前播放时间  00:00
     */
    public String getCurrentTime(){
        if(mMediaPlayer != null){
            int currentPosition = mMediaPlayer.getCurrentPosition();//当前进度，毫秒值为单位
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");//格式化 00:00
            return simpleDateFormat.format(currentPosition);
        }
        return "00:00";
    }

    /**
     * 获得总时间  00:00
     */
    public String getDurationTime(){
        if(mMediaPlayer != null){
            int currentPosition = mMediaPlayer.getDuration();//总时间，毫秒值为单位
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");//格式化 00:00
            return simpleDateFormat.format(currentPosition);
        }
        return "00:00";
    }

    /**
     * 获得进度的百分比 0-100     当前进度*100/总时长
     * @return
     */
    public int getProgress(){
        if(mMediaPlayer != null){
            return mMediaPlayer.getCurrentPosition()*100/mMediaPlayer.getDuration();
        }
        return 0;
    }

    /**
     * 根据进度音乐播放到指定进度
     * @param progress 0-100
     */
    public void seekTo(int progress){
        if(mMediaPlayer != null){
            int i = progress * mMediaPlayer.getDuration() / 100;
            mMediaPlayer.seekTo(i);
        }
    }

    //页面销毁 释放音乐的资源
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mTimer != null){
            mTimer.cancel();//取消定时器
            mTimer = null;
        }
        if(mMediaPlayer != null){
            mMediaPlayer.release();//释放音乐的资源
            mMediaPlayer = null;
        }
    }
}